package com.fyzk.activity.lottery.jc.football.newJz;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseFragment;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.lottery.jc.football.JCInfo;
import com.fyzk.activity.user.NetProgressView;
import com.fyzk.activity.zhifu.JCBasePayActivity;
import com.fyzk.bean.JCZQResponseInfo;
import com.fyzk.betcode.AppLotteryCodeListManager;
import com.fyzk.interfaces.ReTryInterface;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.IntentParamUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import http.Common.CommandUtil;
import http.StringResultBean;

import static com.tyjc.lottery.R.id.info;
import static com.tyjc.lottery.R.id.jcz_btm_xuanding;

//import com.fyzk.utils.LogUtil;

/**
 * 竞彩足球重构 基类
 */
@ContentView(R.layout.layout_fragment_jc)
public abstract class JCZQBaseFragment extends BaseFragment implements ReTryInterface {

    @ViewInject(R.id.jc_vp_netprogressview)
    protected NetProgressView mVi_netView;
    // 中部的对阵列表
    @ViewInject(R.id.buy_jc_main_listview)
    protected ExpandableListView center_list;
    protected int minChangCi = 2;

    @ViewInject(R.id.jcbf_select_guoguan)
    private RadioButton rb_gg;// 过关投注
    @ViewInject(R.id.jcbf_select_danguan)
    private RadioButton rb_dg;// 单关投注
    @ViewInject(R.id.jcbf_radioGroup)
    public RadioGroup rb_gb;//


    // 底部
    @ViewInject(R.id.jcz_btm_changci)
    protected TextView btm_changCi;
    @ViewInject(R.id.jcz_btm_tishi)
    protected TextView btm_tiShi;
    protected int changCiNum = 0;
    @ViewInject(R.id.jcz_btm_clear)
    protected TextView btm_clear;
    @ViewInject(jcz_btm_xuanding)
    protected TextView btm_xuanDing;


    public static final String RESULT_MOREN = "";
    public static final String RESULT_SPLIT = ",";

    public ArrayList<JCZQResponseInfo> infos = new ArrayList<>();
    public static List<JCInfo> matchs = new ArrayList<>();
    public ArrayList<JCZQResponseInfo> infos_all = new ArrayList<>();
    public List<String> betcodes = new ArrayList<>();


    public AlertDialog dialog = null;
    public ArrayList<String> teams = new ArrayList<>();
    public ArrayList<String> teams_sel = new ArrayList<>();
    private boolean isDanguan;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
    }

    @Override
    public void onDestroy() {
        AppLotteryCodeListManager.getInstance().getList().clear();
        AppLotteryCodeListManager.betType = AppLotteryCodeListManager.FIRSTENTER;
        AppLotteryCodeListManager.chooseId = 0;
        super.onDestroy();
    }

    protected void net(boolean checkedChanged) {
        if (infos.size() <= 0 || checkedChanged) {
            mVi_netView.waiting();
            findJczqRace();
        } else {
            notifyList();
        }
    }


    protected void net() {
        if (infos.size() <= 0) {
            if (mVi_netView != null) {
                mVi_netView.waiting();
            }
            findJczqRace();
        } else {
            notifyList();
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        return x.view().inject(this, inflater, container);//xutil注解;
    }


    private void findJczqRace() {
        JSONObject params = new JSONObject();
        try {
            params.put("lotteryType", getLotteryType());
            if (isDanguan()) {
                params.put("type", "01");
            } else {
                params.put("type", "02");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpPostJson(CommandUtil.JCZQGAME_QUEUE, Commands.FINDJCZQRACE, params, true);
    }

    /**
     * 初始化 赛事对阵
     */
    protected void initGameQueueView() {
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        adapterChange(infos);
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        if (resultBean.getErrorcode().equals("0")) {
            if (null != mVi_netView) {
                mVi_netView.dismiss();
            }
            try {
                JSONObject obj = new JSONObject(resultBean.getData());
                Iterator<String> iterator = obj.keys();
                infos_all.clear();
                infos.clear();
                ArrayList<Integer> dateArray = new ArrayList<>();
                while (iterator.hasNext()) {
                    dateArray.add(Integer.parseInt(iterator.next()));
                }
                Collections.sort(dateArray);
                for (Integer dateInt : dateArray) {
                    JCZQResponseInfo info = new JCZQResponseInfo();
                    org.json.JSONArray array = obj.getJSONArray(dateInt + "");
                    for (int i = 0; i < array.length(); i++) {
                        JCInfo info_team = JSON.parseObject(array.getString(i), JCInfo.class);
                        info_team.addTouZhuInfor();
                        info_team.initBtnHGPojo(getLotteryType());
                        info.matchDatas.add(info_team);
                        info.matchTime = dateInt + "";
                        info.phaseNo = dateInt + "";
                        info.lotteryType = getLotteryType();
                        info.matchWeekday = info_team.getOfficialWeekDay();
                    }
                    infos_all.add(info);
                }
                infos.addAll(infos_all);
                initGameQueueView();
                if(infos.isEmpty()){
                    mVi_netView.noneRecord("该玩法暂无比赛");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


        } else {
            mVi_netView.fail(resultBean.getMsg());
        }
    }

    @Override
    public void onFailure(int requestCode, String error_code, String message) {
        if (error_code.equals("900003")) {
            infos_all.clear();
            infos.clear();
            adapterChange(infos);
            mVi_netView.noneRecord(message);
        } else {
            mVi_netView.fail(message);
        }
    }


    public void reTry() {
        // TODO Auto-generated method stub
        net();
    }


    public ArrayList<String> getTeams() {

        for (JCZQResponseInfo info : infos_all) {
            for (JCInfo info_team : info.matchDatas) {
                if (!teams.contains(info_team.getMatchName())) {
                    teams.add(info_team.getMatchName());
                }
            }
        }
        return teams;
    }

    public boolean isDanguan() {
        return isDanguan;
    }

    public void setDanguan(boolean isDanguan) {
        this.isDanguan = isDanguan;
    }

    public abstract void notifyList();


    private void toZhiFu() {
        Intent intent = new Intent(getContext(), getZhiFuActivity());
        JCBasePayActivity.infos.clear();
        for(JCInfo info : matchs){
            if(info.getOnclikNum()>0){
                JCBasePayActivity.infos.add(info);
            }
        }
        intent.putExtra(IntentParamUtils.LOTTERYID, getLotteryType());
        intent.putExtra(IntentParamUtils.TYPE_GUOGUAN, isDanguan());
        startActivityForResult(intent, IntentParamUtils.JC_PAY);
    }

    protected void init(View view) {
        // TODO Auto-generated method stub
        rb_gb.setOnCheckedChangeListener(listener);
        btm_changCi.setText(changCiNum + "场");
        btm_xuanDing.setOnClickListener(bottomClickListener);
        btm_clear.setOnClickListener(bottomClickListener);

        mVi_netView.setRetryInterface(this);
        initMinChangci();
    }

    int guanChangeNum = 0;//过关方式 改变的次数

    OnCheckedChangeListener listener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub
            guanChangeNum++;
            switch (checkedId) {
                case R.id.jcbf_select_guoguan:// 过关
                    setDanguan(false);
                    break;
                case R.id.jcbf_select_danguan:// 单关
                    setDanguan(true);
                    break;
            }
            if (!JCBasePayActivity.isZhifu) {
                net(true);
                clearSelect();
            } else if (JCBasePayActivity.isZhifu && guanChangeNum > 1) {
                net(true);
                clearSelect();
            } else {
                zhifuBackNotify();
            }
            initMinChangci();
        }
    };

    //支付页面返回 投注页面后  更新list
    private void zhifuBackNotify() {
        initGameQueueView();
        adapterChange(infos);
    }


    protected String getResult(JCInfo infor) {
        return "";
    }

    public OnClickListener bottomClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case jcz_btm_xuanding:
                    xuanding();
                    break;
                case R.id.jcz_btm_clear:
                    clearSelect();
                    break;
            }
        }
    };

    private void xuanding() {
        if (changCiNum < minChangCi) {
            AppToast.getToast().show("至少选择" + minChangCi + "场比赛");
        } else {// 跳转支付界面
            if (!JCBasePayActivity.isZhifu) {
                matchs.clear();
                for (JCZQResponseInfo info : infos) {
                    matchs.addAll(info.matchDatas);
                }
                toZhiFu();
            }
        }
    }

    public void clearSelect() {
        if(null!=infos){
            clearTouZhu(infos);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == IntentParamUtils.JC_ADDMORE) {
            adapterChange(infos);
            notifyList();
        }
    }

    // 初始化 最小选择场次 （单关一场 过关两场）
    protected void initMinChangci() {
        minChangCi = isDanguan() ? 1 : 2;
        btm_tiShi.setText(String.format(Locale.CHINESE,"至少选择%d场比赛", minChangCi));
    }

    /**
     * 选择清除后将列表子项 设置成默认
     */
    public void setItemDefault(JCInfo obj) {
        obj.setOnclikNum(0);
        obj.setHg_more(0);
        obj.setResult(RESULT_MOREN);
        obj.setDan(false);
        Collection<JCInfo.SPInfo> spInfos = obj.btnHGPojo.values();
        Iterator<JCInfo.SPInfo> iterator = spInfos.iterator();

        while (iterator.hasNext()) {
            JCInfo.SPInfo spInfo = iterator.next();
            spInfo.isSel = false;
        }
        for (int i = 0; i < obj.getTouZhuInfor().size(); i++) {
            obj.getTouZhuInfor().get(i).setSelect(false);
        }
    }

    /**
     * 清空
     *
     * @param infors
     */
    private void clearTouZhu(List<JCZQResponseInfo> infors) {
        try {
            if (null == infos) {
                infos = new ArrayList<>();
            } else {
                if (infors.size() > 0) {
                    for (int i = 0; i < infors.size(); i++) {
                        JCZQResponseInfo info = infors.get(i);
                        if (null != info) {
                            for (JCInfo info_team : info.matchDatas) {
                                setItemDefault(info_team);
                            }
                        }
                    }
                }
            }
            adapterChange(infors);
        } catch (Exception e) {
            e.printStackTrace();
        }
        changCiNum = 0;
        btm_changCi.setText(changCiNum + "场");
    }

    protected int getTitleStringRes() {
        // TODO Auto-generated method stub
        return 0;
    }

    protected abstract Class getZhiFuActivity();

    protected int getLotteryType() {
        // TODO Auto-generated method stub
        return 0;
    }

    protected abstract void adapterChange(List<JCZQResponseInfo> infos);

    public void onFilter(ArrayList<String> teams_sel) {
        infos.clear();
        for (int i = 0; i < infos_all.size(); i++) {
            JCZQResponseInfo info_ = infos_all.get(i).copy();
            if (!infos.contains(info_)) {
                infos.add(info_);
            }
            List<JCInfo> datas = infos_all.get(i).matchDatas;
            for (JCInfo data : datas) {
                if (teams_sel.contains(data.getMatchName())) {
                    infos.get(i).matchDatas.add(data);
                }
            }
        }
        notifyList();
    }
}